package edu.stanford.prpl.common;

import org.apache.log4j.Logger;

import java.io.*;
import java.net.URL;
import java.util.Calendar;
import java.util.Properties;

public class PRPLProperties {

	private static Properties prop = new Properties();
	private static final String DEFAULT_PROP_FILE = "prpl.properties";
	private static final Logger LOG = Logger.getLogger(PRPLProperties.class);

	static {
		loadProperties(DEFAULT_PROP_FILE);
	}

	public static String getProperty(String key) {
		return prop.getProperty(key);
	}

	public static String getProperty(String key, String defaultVal) {
		return prop.getProperty(key, defaultVal);
	}

	public static void setProperty(String key, String val) {
		prop.setProperty(key, val);
	}

	public static void storeProperties(File file) {
		try {
			FileOutputStream out = new FileOutputStream(file);
			String comments = "Updated on " + Calendar.getInstance().toString();
			prop.store(out, comments);
		} catch (Exception e) {
			LOG.error("Error storing properties to file " + file);
		}
	}

	public static void storeProperties(String resourcePath) {
		// URL propURL = ClassLoader.getSystemClassLoader().getResource(resourcePath);
		URL propURL = PRPLProperties.class.getResource(resourcePath);
		try {
			String comments = "Updated on " + Calendar.getInstance().toString();
			FileOutputStream out = new FileOutputStream(propURL.getPath());
			prop.store(out, comments);
		} catch (Exception e) {
			LOG.error("Error storing properties to path " + resourcePath);
		}
	}

	public static void loadProperties(String resourcePath) {

		// Try classpath -> working dir -> home dir
		try {
			InputStream in = PRPLProperties.class.getResourceAsStream(resourcePath);
			// InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
			prop.load(in);
		} catch (Exception e) {
			try {
				FileInputStream in = new FileInputStream(resourcePath);
				prop.load(in);
			} catch (IOException e1) {

				try {
					String homeDir = System.getProperty("user.home");
					FileInputStream in = new FileInputStream(homeDir + File.pathSeparator + resourcePath);
					prop.load(in);

				} catch (IOException e2) {
					LOG.error("Error loading properties from path " + resourcePath);
					return;

				}
			}
		}
		LOG.debug("Loaded properties from path " + resourcePath);
	}
}
